package com.ymt.fmd.platform.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import com.ymt.fmd.appboot.prop.FmdProperties;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ymt.fmd.platform.dao.mysql.CustomSQLDao;
import com.ymt.fmd.util.Const;
import com.ymt.fmd.util.DhxUtil;
import com.ymt.fmd.util.ExcelUtil;

@Service
@EnableConfigurationProperties(value = {FmdProperties.class})
public class ImportExportService {
	
	private Logger logger = Logger.getLogger(this.getClass().getName());

	@Autowired
	private FmdProperties fmdProperties;

	@Autowired
	private CustomSQLDao csDao;
	
	public void export(String piId, String paramStr, String lang) throws Exception {
		FileOutputStream os = new FileOutputStream(new File("d:/test.xls"));
        List<List<String>> data = new ArrayList<List<String>>();
		JSONObject param = JSONObject.parseObject(paramStr);
		String m = param.getString("model");
		JSONArray columns = param.getJSONArray("columns");
//		int timezoneOffset = param.getInt("timezoneOffset");
		String orderby = DhxUtil.parseGridOrderBy(param.getString("ordercolumns"));
		String[] cols = new String[]{};
		cols = (String[]) columns.toArray(cols);
		String head = StringUtils.join(cols,",");
		String sql = "select " + head + " from "+m+" where ts_id='"+piId+"'";
		//count
//		int total = Integer.parseInt(csDao.selectCount(sql).get(0).get("COUNT").toString());
		//query
		if (orderby!=null && orderby.length()>0) {
			sql += orderby;
		}
		List<Map<String,?>> rs = csDao.selectAll(sql);
		List rlist = null;
	        for(int i = 0;i<rs.size();i++){
//	            rlist = ExcelUtil.testMapVoid(rs.get(0));          
	            data.add(rlist);
	        }
//	    ExcelUtil.exportToExcel(os, data,columns);
	    logger.finer("export data:"+data);
	}
	
	public void importExcel(String filePath,String fileType,String model) throws Exception{
		FileInputStream is = new FileInputStream(new File(filePath));
		if(fileType.equals("xls")){
//			List<List<String>> data = ExcelUtil.importFromExcel(is);
//			logger.finer("importExcel data:"+data);
			
//			String sql = "insert into " + head + " from "+m+" where ts_id='"+piId+"'";
			
		}else{
//			List<List<String>> data = ExcelUtil.importEx(filePath);
//			logger.finer("importExcel data:"+data);
		}
	}

	public String parseExcelOnServer(HttpServletRequest req) {
		String rtnMsg = "";
		JSONObject rtn = new JSONObject();
		// 设置接收的编码格式
		try {
			req.setCharacterEncoding(Const.ENCODING);
			// 创建文件项工厂对象
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 设置临时保存解析出的数据大小
			factory.setSizeThreshold(4096); // 设置缓冲区大小，这里是4kb,-1无上限
			factory.setRepository(new File(fmdProperties.getImpexpTmpDir()));// 设置缓冲区目录
			// 创建文件上传控制器(Apache组建文件上传的核心类 )
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 解决上传文件名的中文乱码
			upload.setHeaderEncoding(Const.ENCODING);
			// 设置最大文件尺寸,这里设5MB
			upload.setSizeMax(5 * 1024 * 1024);

			@SuppressWarnings("unchecked")
			List<FileItem> items = upload.parseRequest(req);// 得到所有的文件
			Iterator<FileItem> i = items.iterator();
			while (i.hasNext()) {
				FileItem fi = (FileItem) i.next();
				if (fi != null) {
					// 获取文件名
					/*String fileName = fileNameFull.substring(0,
							fileNameFull.lastIndexOf("."));
					logger.finer("parseExcelOnServer fileName="+fileName);
					// 获取文件扩展名
					String extName = fileNameFull.substring(fileNameFull
							.lastIndexOf("."));
					String filType = fileNameFull.substring(
							fileNameFull.lastIndexOf(".") + 1,
							fileNameFull.length());
					logger.finer("parseExcelOnServer extName="+extName);
					logger.finer("parseExcelOnServer filType="+filType);*/
					JSONArray data = ExcelUtil.parseExcel(fi.getOutputStream());
					rtn.put("data", data);
				}
			}
		} catch (UnsupportedEncodingException e) {
			rtnMsg = "UnsupportedEncodingException";
			e.printStackTrace();
		} catch (IOException e) {
			rtnMsg = "IOException";
			e.printStackTrace();
		} catch (FileUploadException e) {
			rtnMsg = "FileUploadException";
			e.printStackTrace();
		} catch (Exception e) {
			rtnMsg = "Exception";
			e.printStackTrace();
		}
		if (rtnMsg.length()>0) {
			rtn.put("result", false);
			rtn.put("msg", rtnMsg);
		} else {
			rtn.put("result", true);
		}
		return rtn.toJSONString();
	}
}
